package manager

import (
	"errors"

	"gddgame.cc/galaxy/binocle"
	"gddgame.cc/galaxy/common/bootstrap"
	. "gddgame.cc/galaxy/common/dsl/web"
	"gddgame.cc/galaxy/core/config"
	"gddgame.cc/galaxy/core/routers"
	"gddgame.cc/galaxy/server/composer"
	"gddgame.cc/galaxy/server/web"
	"gddgame.cc/galaxy/utils"
	"github.com/toolkits/file"
)

const (
	Version = "1.0.0"
)

type Config struct {
	Address          string `json:"address"`
	Node             string `json:"node"`
	UploadUrl        string `json:"upload_url"`
	UploadPath       string `json:"upload_path"`
	DeployPath       string `json:"deploy_path"`
	ProjectToolsPath string `json:"project_tools_path"`
}
type Component struct {
	Config *Config

	Web web.Engine `inject:""`

	composer.Composer `inject:""`

	Boot *bootstrap.Boot `inject:""`

	Binocle binocle.Core `inject:""`
}

func (c *Component) Init(register composer.Register, builder composer.Builder) error {
	// 注册为控制中心
	if err := c.Binocle.Config(binocle.Config{
		Name:    "manager",
		Node:    c.Config.Node,
		Version: Version,
	}); err != nil {
		return err
	}

	core := c.Binocle.Client()

	if err := builder.BindInstance("boot", c.Boot); err != nil {
		return err
	}
	if err := builder.BindInstance(binocle.DefaultCore, core); err != nil {
		return err
	}

	// 初始化路径
	config.UploadPath = utils.Abs(c.Config.UploadPath)
	config.UploadUrl = c.Config.UploadUrl
	if err := utils.Mkdir(config.UploadPath); err != nil {
		return err
	}

	config.DeployPath = utils.Abs(c.Config.DeployPath)
	if err := utils.Mkdir(config.DeployPath); err != nil {
		return err
	}

	config.ProjectToolsPath = utils.Abs(c.Config.ProjectToolsPath)
	if !file.IsExist(config.ProjectToolsPath) {
		return errors.New("Project tools is empty")
	}

	register.Attach(c.Web.Register(c.Config.Address, func(r web.Router, handler web.RouterHandler) error {
		swagger := BuildSwagger(builder, r, handler, &SwaggerConfig{})

		r.FileServer(c.Config.UploadPath, c.Config.UploadUrl)

		if err := routers.ManageHandler("/manage", builder, swagger("/manage"), c.Boot); err != nil {
			return err
		}
		if err := routers.AppHandler("/app", builder, swagger("/app")); err != nil {
			return err
		}
		return nil
	}))

	return nil
}
